package com.fhc.usb

object HexUtil {
    fun hexStringToBytes(hexString: String?): ByteArray? {
        if (hexString.isNullOrEmpty()) {
            return null
        }
        val upperString = hexString.uppercase()
        val length = upperString.length / 2
        val hexChars = upperString.toCharArray()
        return ByteArray(length) { i ->
            val pos = i * 2
            (charToByte(hexChars[pos]) shl 4 or charToByte(hexChars[pos + 1])).toByte()
        }
    }

    private fun charToByte(c: Char): Int = "0123456789ABCDEF".indexOf(c)

    fun bytesToHexString(b: ByteArray?): String? {
        if (b == null || b.isEmpty()) {
            return null
        }
        return buildString {
            b.forEach { byte ->
                val value = byte.toInt() and 0xFF
                val hv = value.toString(16)
                if (hv.length < 2) {
                    append(0)
                }
                append("0x").append(hv).append(" ")
            }
        }
    }

    fun toByteString(b: Byte): String {
        val hex = (b.toInt() and 0xFF).toString(16)
        return if (hex.length == 1) "0$hex" else hex
            .uppercase()
    }
}